﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitKernel.CurveUtility.CurveGroupSuite;
using YJKRevitKernel.RevitTopologySuite;

namespace YJKRevitKernel.SampleAndTest
{
	[Transaction(TransactionMode.Manual)]
	public class CmdRevitDetailCurveConvexHullPolygonFind : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			Application application2 = commandData.Application.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			List<Element> list = activeUIDocument.Selection.PickElementsByRectangle("框选详图线").ToList<Element>();
			List<Curve> list2 = new List<Curve>();
			foreach (Element element in list)
			{
				if (element is DetailCurve)
				{
					list2.Add((element as DetailCurve).GeometryCurve);
				}
			}
			List<List<Curve>> list3 = CurveGroupManger.GroupCurvesByIntersection(list2);
			bool flag = false;
			foreach (List<Curve> lstInputCurves in list3)
			{
				RevitPolygonDataBean item = null;
				if (new RevitPolygonFinder().TryGetConvexHullPolygon(lstInputCurves, out item, 3))
				{
					Transaction transaction = new Transaction(document, "test");
					try
					{
						transaction.Start();
						if (!flag)
						{
							IEnumerable<ElementId> source = from n in list
							select n.Id;
							document.Delete(source.ToList<ElementId>());
							flag = true;
						}
						List<RevitPolygonDataBean> list4 = new List<RevitPolygonDataBean>();
						list4.Add(item);
						FilledRegionType useType = CmdRevitFilledRegionTopology.FindFilledRegionType(document);
						CmdRevitFilledRegionTopology.CreatFilledRegion(document, list4, useType);
						transaction.Commit();
					}
					catch (Exception)
					{
						transaction.RollBack();
					}
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
